const Base = require('./base.js');

module.exports = class extends Base {
  async indexAction() {
    return this.redirect('posts/list');
  }

  async searchAction() {
    const keywords = this.get('s');
    const posts = await think.model('contents').alias('c').field('c.*, m.name as metas_name').where({ 'c.type': 'post', 'c.title|c.text': ['LIKE', `%${keywords}%`]}).order('`order` DESC').join({
      table: 'metas',
      join: 'inner',
      as: 'm',
      on: ['mid', 'mid']
    }).select();
    posts.map(post => {
      post.created = think.datetime(post.created * 1000);
      return post;
    });
    this.assign('posts', posts);
    this.setPageTile(keywords);
    return this.display('posts_list.html');
  }

  /**
   * 列表页面
   */
  async listAction() {
    // 普通列表、标签文章列表、分类文章列表、搜索文章、
    return this.display();
  }

  async detailAction() {
    const id = this.get('id');
    const post = await think.model('contents').alias('c')
      .field('c.*, m.name as metas_name')
      .where({ 'c.type': 'post', 'c.cid': id}).join({
        table: 'metas',
        join: 'inner',
        as: 'm',
        on: ['mid', 'mid']
      }).find();
    if (think.isEmpty(post)) {
      return this.redirect('/');
    }
    post.created = think.datetime(post.created * 1000);
    this.assign('post', post);
    this.setPageTile(post.title, true);
    return this.display('posts_detail.html');
  }
};
